<template>
	<view class="login-container">
		<view class="login-form">
			<!-- Logo和标题 -->
			<view class="header">
				<view class="logo">
					<uni-icons type="settings" size="48" color="#409EFF"></uni-icons>
				</view>
				<text class="title">管理员登录</text>
				<text class="subtitle">请输入您的登录凭据</text>
			</view>

			<!-- 登录表单 -->
			<uni-forms ref="loginForm" :modelValue="form" :rules="rules">
				<uni-forms-item name="username" label="用户名">
					<uni-easyinput 
						v-model="form.username" 
						placeholder="请输入用户名"
						:clearable="true"
						prefixIcon="person"
					></uni-easyinput>
				</uni-forms-item>

				<uni-forms-item name="password" label="密码">
					<uni-easyinput 
						v-model="form.password" 
						type="password"
						placeholder="请输入密码"
						:clearable="true"
						prefixIcon="locked"
					></uni-easyinput>
				</uni-forms-item>

				<uni-forms-item name="captcha" label="验证码" v-if="showCaptcha">
					<view class="captcha-container">
						<uni-easyinput 
							v-model="form.captcha" 
							placeholder="请输入验证码"
							:clearable="true"
						></uni-easyinput>
						<view class="captcha-image" @click="refreshCaptcha">
							<text class="captcha-text">{{ captchaText }}</text>
						</view>
					</view>
				</uni-forms-item>

				<uni-forms-item>
					<view class="remember-container">
						<uni-data-checkbox 
							v-model="form.rememberMe" 
							:localdata="[{value: true, text: '记住我'}]"
						></uni-data-checkbox>
					</view>
				</uni-forms-item>
			</uni-forms>

			<!-- 登录按钮 -->
			<button 
				class="login-btn" 
				:loading="loginLoading" 
				@click="handleLogin"
				:disabled="loginLoading"
			>
				{{ loginLoading ? '登录中...' : '登录' }}
			</button>

			<!-- 其他操作 -->
			<view class="footer">
				<text class="forgot-password" @click="handleForgotPassword">忘记密码？</text>
			</view>
		</view>

		<!-- 背景装饰 -->
		<view class="background-decoration">
			<view class="circle circle-1"></view>
			<view class="circle circle-2"></view>
			<view class="circle circle-3"></view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			form: {
				username: '',
				password: '',
				captcha: '',
				rememberMe: []
			},
			rules: {
				username: {
					rules: [
						{
							required: true,
							errorMessage: '用户名不能为空'
						},
						{
							minLength: 3,
							maxLength: 20,
							errorMessage: '用户名长度在3-20之间'
						}
					]
				},
				password: {
					rules: [
						{
							required: true,
							errorMessage: '密码不能为空'
						},
						{
							minLength: 6,
							maxLength: 20,
							errorMessage: '密码长度在6-20之间'
						}
					]
				},
				captcha: {
					rules: [
						{
							required: true,
							errorMessage: '验证码不能为空'
						}
					]
				}
			},
			loginLoading: false,
			showCaptcha: false,
			captchaText: '',
			loginAttempts: 0
		}
	},
	onLoad() {
		this.initPage()
		this.generateCaptcha()
	},
	methods: {
		// 初始化页面
		initPage() {
			// 检查是否记住了用户名
			const savedUsername = uni.getStorageSync('admin_username')
			if (savedUsername) {
				this.form.username = savedUsername
				this.form.rememberMe = [true]
			}
			
			// 检查登录失败次数
			const attempts = uni.getStorageSync('login_attempts') || 0
			this.loginAttempts = attempts
			this.showCaptcha = attempts >= 3
		},

		// 生成验证码
		generateCaptcha() {
			const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
			let result = ''
			for (let i = 0; i < 4; i++) {
				result += chars.charAt(Math.floor(Math.random() * chars.length))
			}
			this.captchaText = result
		},

		// 刷新验证码
		refreshCaptcha() {
			this.generateCaptcha()
			this.form.captcha = ''
		},

		// 处理登录
		async handleLogin() {
			try {
				// 表单验证
				await this.$refs.loginForm.validate()
				
				// 验证码检查
				if (this.showCaptcha && this.form.captcha.toUpperCase() !== this.captchaText) {
					uni.showToast({
						title: '验证码错误',
						icon: 'none'
					})
					this.refreshCaptcha()
					return
				}

				this.loginLoading = true

				// 调用登录云函数
				const result = await uniCloud.callFunction({
					name: 'adminLogin',
					data: {
						username: this.form.username,
						password: this.form.password
					}
				})

				if (result.result.success) {
					// 登录成功
					const { token, userInfo } = result.result.data
					
					// 保存登录信息
					uni.setStorageSync('admin_token', token)
					uni.setStorageSync('admin_userInfo', userInfo)
					
					// 记住用户名
					if (this.form.rememberMe.includes(true)) {
						uni.setStorageSync('admin_username', this.form.username)
					} else {
						uni.removeStorageSync('admin_username')
					}
					
					// 清除登录失败记录
					uni.removeStorageSync('login_attempts')
					
					uni.showToast({
						title: '登录成功',
						icon: 'success'
					})
					
					// 跳转到首页
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/index/index'
						})
					}, 1500)

				} else {
					throw new Error(result.result.message || '登录失败')
				}

			} catch (error) {
				console.error('登录失败:', error)
				
				// 记录登录失败次数
				this.loginAttempts++
				uni.setStorageSync('login_attempts', this.loginAttempts)
				
				// 3次失败后显示验证码
				if (this.loginAttempts >= 3) {
					this.showCaptcha = true
					this.generateCaptcha()
				}
				
				uni.showToast({
					title: error.message || '登录失败，请检查用户名和密码',
					icon: 'none',
					duration: 3000
				})
				
				// 刷新验证码
				if (this.showCaptcha) {
					this.refreshCaptcha()
				}
			} finally {
				this.loginLoading = false
			}
		},

		// 忘记密码
		handleForgotPassword() {
			uni.showModal({
				title: '找回密码',
				content: '请联系系统管理员重置密码',
				showCancel: false,
				confirmText: '确定'
			})
		}
	}
}
</script>

<style scoped>
.login-container {
	min-height: 100vh;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 20px;
	position: relative;
	overflow: hidden;
}

.login-form {
	width: 100%;
	max-width: 400px;
	background: white;
	border-radius: 16px;
	padding: 40px 32px;
	box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
	backdrop-filter: blur(10px);
	z-index: 2;
	position: relative;
}

/* 头部样式 */
.header {
	text-align: center;
	margin-bottom: 40px;
}

.logo {
	margin-bottom: 16px;
}

.title {
	font-size: 28px;
	font-weight: bold;
	color: #333;
	display: block;
	margin-bottom: 8px;
}

.subtitle {
	font-size: 14px;
	color: #666;
	display: block;
}

/* 表单样式 */
.captcha-container {
	display: flex;
	gap: 12px;
	align-items: center;
}

.captcha-image {
	width: 100px;
	height: 40px;
	background: linear-gradient(45deg, #f0f0f0, #e0e0e0);
	border: 1px solid #ddd;
	border-radius: 4px;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	user-select: none;
	flex-shrink: 0;
}

.captcha-text {
	font-size: 16px;
	font-weight: bold;
	color: #666;
	letter-spacing: 2px;
}

.remember-container {
	margin-top: 8px;
}

/* 登录按钮 */
.login-btn {
	width: 100%;
	height: 48px;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: white;
	border: none;
	border-radius: 8px;
	font-size: 16px;
	font-weight: 600;
	margin-top: 24px;
	transition: all 0.3s ease;
}

.login-btn:hover:not(:disabled) {
	transform: translateY(-2px);
	box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
}

.login-btn:disabled {
	opacity: 0.7;
	cursor: not-allowed;
}

/* 底部 */
.footer {
	text-align: center;
	margin-top: 24px;
}

.forgot-password {
	color: #409EFF;
	font-size: 14px;
	cursor: pointer;
	text-decoration: none;
	transition: color 0.2s;
}

.forgot-password:hover {
	color: #66b1ff;
	text-decoration: underline;
}

/* 背景装饰 */
.background-decoration {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	pointer-events: none;
	z-index: 1;
}

.circle {
	position: absolute;
	border-radius: 50%;
	background: rgba(255, 255, 255, 0.1);
	animation: float 6s ease-in-out infinite;
}

.circle-1 {
	width: 200px;
	height: 200px;
	top: 10%;
	left: 10%;
	animation-delay: 0s;
}

.circle-2 {
	width: 150px;
	height: 150px;
	top: 60%;
	right: 10%;
	animation-delay: 2s;
}

.circle-3 {
	width: 100px;
	height: 100px;
	bottom: 20%;
	left: 60%;
	animation-delay: 4s;
}

@keyframes float {
	0%, 100% {
		transform: translateY(0px) rotate(0deg);
	}
	50% {
		transform: translateY(-20px) rotate(180deg);
	}
}

/* 响应式设计 */
@media (max-width: 480px) {
	.login-form {
		padding: 32px 24px;
		margin: 20px;
	}
	
	.title {
		font-size: 24px;
	}
	
	.captcha-container {
		flex-direction: column;
		align-items: stretch;
	}
	
	.captcha-image {
		width: 100%;
		margin-top: 8px;
	}
}
</style>
